using UnityEngine;
using UnityEngine.Serialization;

public class Player : MonoBehaviour
{
    // 控制飞机动画的变量
    // 帧率（每秒播放的帧数，如 10 表示每秒切换 10 张图片）
    public int frameRate = 10;
    public Sprite[] idleSprites;
    public SpriteRenderer spriteRenderer;
    public Animator blinkAnimator;
    private float _timer = 0;
    private int _currentFrame = 0;


    // 控制飞机移动的变量
    private bool _isMouseDown = false;
    private Vector3 _lastMousePosition;

    // 单次超级奖励的持续时间变量
    public float superGunDuration = 5f;
    public float superGunTimeLeft = 0f;
    public GameObject superLeftGun;
    public GameObject superRightGun;

    public GameObject topGun;

    // 玩家血量
    public int hp = 5;

    // 无敌 无敌时间参数 
    private bool _invincible = false;
    public float invincibleDuration = 3f;

    private float _invincibleTimeLeft = 0f;

    // //无敌闪烁频率
    // public float invincibleFlashRate = 5f;
    // private float _invincibleFlashTimer = 0f;

    //死亡动画参数
    public Sprite[] deathSprites;
    public bool isDead = false;

    // 获得奖励的音效播放器
    public AudioSource getBombAudio;
    public AudioSource getDoubleLaterAudio;
    public AudioSource damageAudio;


    void Start()
    {
        spriteRenderer = GetComponent<SpriteRenderer>();
        blinkAnimator = GetComponent<Animator>();
    }

    void Update()
    {
        IdleAnimationUpdate();
        MoveUpdate();
        // 超级枪状态倒计时
        SuperGunUpdate();
        InvincibleUpdate();
        DeathAnimationUpdate();
        PlayerHpUpdate();
    }

    void PlayerHpUpdate()
    {
        GameManager.Instance.ShowPlayerHp(hp);
    }

    void SuperGunUpdate()
    {
        if (superGunTimeLeft <= 0)
        {
            //正常状态
            return;
        }

        superGunTimeLeft -= Time.deltaTime;
        if (superGunTimeLeft <= 0)
        {
            superGunTimeLeft = 0;
            //恢复正常
            TransformGunToNormal();
        }
        else
        {
            //todo nothing
        }
    }

    void IdleAnimationUpdate()
    {
        if (!isDead)
        {
            _timer = _timer + Time.deltaTime;
            if (_timer > 1f / frameRate)
            {
                _timer = _timer - 1f / frameRate;
                _currentFrame = (_currentFrame + 1) % idleSprites.Length;
                spriteRenderer.sprite = idleSprites[_currentFrame];
            }
        }
    }

    void MoveUpdate()
    {
        if (GameManager.Instance.gameState != GameManager.GameState.Playing || isDead)
        {
            return;
        }

        // 判断鼠标左键是否按下状态
        if (Input.GetMouseButtonDown(0))
        {
            _isMouseDown = true;
            // 记录当前鼠标位置
            // _lastMousePosition = Input.mousePosition;
        }

        if (Input.GetMouseButtonUp(0))
        {
            _isMouseDown = false;
            _lastMousePosition = Vector3.zero;
        }

        // 如果鼠标是按下的状态则每帧移动
        if (_isMouseDown)
        {
            var screenToWorldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            if (_lastMousePosition == Vector3.zero)
            {
            }
            else
            {
                Vector3 offset = screenToWorldPoint - _lastMousePosition;
                transform.position = AddOffset(transform.position, offset);
            }

            _lastMousePosition = screenToWorldPoint;
        }
    }

    Vector3 AddOffset(Vector3 now, Vector3 offset)
    {
        //使用mathf 限制x y 的范围
        now.x = Mathf.Clamp(now.x + offset.x, -2.13f, 2.13f);
        now.y = Mathf.Clamp(now.y + offset.y, -3.75f, 3.45f);
        return now;
    }

    void DisableAllGun()
    {
        superLeftGun.SetActive(false);
        superRightGun.SetActive(false);
        topGun.SetActive(false);
    }

    void TransformGunToSuper()
    {
        superLeftGun.SetActive(true);
        superRightGun.SetActive(true);
        topGun.SetActive(false);
    }

    void TransformGunToNormal()
    {
        superLeftGun.SetActive(false);
        superRightGun.SetActive(false);
        topGun.SetActive(true);
    }

    void TransformToDeath()
    {
        DisableAllGun();
        isDead = true;
        //播放死亡动画
        _invincible = false;
        _timer = 0;
        _currentFrame = 0;
    }

    void TransformToInvincible()
    {
        _invincible = true;
        _invincibleTimeLeft = invincibleDuration;
        // 开启闪烁动画
        blinkAnimator.enabled = true;
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.tag == "Award")
        {
            var award = collision.gameObject.GetComponent<Award>();
            if (award.awardType == Award.AwardType.SuperGun)
            {
                getDoubleLaterAudio.Play();
                superGunTimeLeft = superGunDuration;
                TransformGunToSuper();
            }
            else
            {
                // 炸弹
                getBombAudio.Play();
                GameManager.Instance.AddBomb();
            }

            Destroy(collision.gameObject);
        }

        if (collision.tag == "Enemy" && !_invincible)
        {
            var enemy = collision.gameObject.GetComponent<Enemy>();
            enemy.TakeDamage();
            hp--;
            if (hp > 0)
            {
                //进入受伤
                // 进入无敌状态
                damageAudio.Play();
                TransformToInvincible();
            }
            else
            {
                TransformToDeath();
            }
        }
    }

    //无敌状态更新
    private void InvincibleUpdate()
    {
        if (_invincible)
        {
            //闪烁效果
            // _invincibleFlashTimer += Time.deltaTime;
            // if (_invincibleFlashTimer > 1f / invincibleFlashRate)
            // {
            //     spriteRenderer.enabled = !spriteRenderer.enabled;
            //     _invincibleFlashTimer = 0f;
            // }
            _invincibleTimeLeft -= Time.deltaTime;
            if (_invincibleTimeLeft <= 0)
            {
                //结束无敌
                _invincible = false;
                // spriteRenderer.enabled = true;
                blinkAnimator.enabled = false;
            }
        }
    }

    private void DeathAnimationUpdate()
    {
        if (isDead)
        {
            {
                _timer = _timer + Time.deltaTime;
                if (_timer > 1f / frameRate)
                {
                    _timer = _timer - Time.deltaTime;
                    _currentFrame++;
                    if (_currentFrame > deathSprites.Length)
                    {
                        // GameOver
                        GameManager.Instance.GameOver();
                    }
                    else
                    {
                        spriteRenderer.sprite = deathSprites[_currentFrame - 1];
                    }
                }
            }
        }
    }
}